import { Injectable } from '@angular/core';
import {environment} from '../../environments/environment';
import {HttpClient} from '@angular/common/http';
import {Observable, tap} from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ProblemService {
  private problemCache: any[] = [];  // 本地缓存问题列表
  private cacheTimestamp: number = 0;  // 缓存时间戳
  constructor(private http: HttpClient) { }

  /**
   * 获取所有问题列表
   */
  getAllProblems(): Observable<any[]> {
    // 如果缓存还有效，直接返回缓存数据
    if (this.shouldUseCache()) {
      return new Observable(observer => {
        observer.next(this.problemCache);
        observer.complete();
      });
    }
    // 否则从后端获取数据并缓存
    return this.http.get<any[]>(environment.apiUrl + '/problems').pipe(
      tap(data => {
        this.problemCache = data;
        this.cacheTimestamp = Date.now(); // 更新缓存时间戳
      })
    );
  }

  /**
   * 获取单个问题的详情
   */
  getProblemById(id: number): Observable<any> {
    const localProblem = this.problemCache.find(p => p.id === id);
    if (localProblem) {
      return new Observable(observer => {
        observer.next(localProblem);
        observer.complete();
      });
    }
    return this.http.get(`${environment.apiUrl}/problems/${id}`);
  }

  /**
   * 判断是否使用缓存数据
   */
  private shouldUseCache(): boolean {
    // 设置缓存过期时间为 5 分钟（300000 毫秒）
    const cacheExpiryTime = 300000;
    return Date.now() - this.cacheTimestamp < cacheExpiryTime;
  }
}
